package com.song.util;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SongHttpConnection {

    public static String handleParam(String mark, String params) throws Exception {
        String result = mark + URLEncoder.encode(params, "utf-8");
        return result;
    }

    /**
     * 接口调用 POST
     */
    public static String httpURLConnectionPOST(String requestUrl, String params) {
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);

            // 设置连接输入流为true
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            connection.connect();

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());

            // 将参数输出到连接
            out.writeBytes(params);

            out.flush();
            out.close();

            // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                sb.append(line).append(System.getProperty("line.separator"));
            }

            System.out.println("====================================================");
            System.out.println(sb.toString().equals("") ? "接口返回结果为空" : sb.toString());
            System.out.println("===========================================================================");

            bf.close();

            connection.disconnect();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return "调用失败";
        }
    }

}
